<?php

/**
 * tpAdmin [a web admin based ThinkPHP5]
 *
 * @author yuan1994 <tianpian0805@gmail.com>
 * @link http://tpadmin.yuan1994.com/
 * @copyright 2016 yuan1994 all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */
//------------------------
// 公共函数
//-------------------------

use think\Session;
use think\Response;
use think\Request;
use think\Url;
use think\Db;

/**
 * CURLFILE 兼容性处理 php < 5.5
 * 一定不要修改、删除，否则 curl 可能无法上传文件
 */
if (!function_exists('curl_file_create')) {

    function curl_file_create($filename, $mimetype = '', $postname = '') {
        return "@$filename;filename="
                . ($postname ?: basename($filename))
                . ($mimetype ? ";type=$mimetype" : '');
    }

}

function urlencod($val) {
    return urlencode($val);
}

function in_strpos($val, $arr) {
    return strpos('!' . $arr, $val);
}

function strip($str) {
    $str = str_replace(array('&lt;p&gt;', '&lt;/p&gt;', '&lt;br&gt;', '&lt;br/&gt;','&amp;nbsp;','&nbsp;'), "", $str);
//$str=htmlspecialchars($str);
    return strip_tags($str);
}


/**
 * flash message
 *
 * flash("?KEY") 判断是否存在flash message KEY 返回bool值
 * flash("KEY") 获取flash message，存在返回具体值，不存在返回null
 * flash("KEY","VALUE") 设置flash message
 * @param string $key
 * @param bool|string $value
 * @return bool|mixed|null
 */
function flash($key, $value = false) {
    $prefix = 'flash_';
    // 判断是否存在flash message
    if ('?' == substr($key, 0, 1)) {
        return Session::has($prefix . substr($key, 1));
    } else {
        $flash_key = $prefix . $key;
        if (false === $value) {
            // 获取flash
            $ret = Session::pull($flash_key);

            return null === $ret ? null : unserialize($ret);
        } else {
            // 设置flash
            return Session::set($flash_key, serialize($value));
        }
    }
}

/**
 * 表格排序筛选
 * @param string $name  单元格名称
 * @param string $field 排序字段
 * @return string
 */
function sort_by($name, $field = '') {
    $sort = Request::instance()->param('_sort');
    $param = Request::instance()->get();
    $param['_sort'] = ($sort == 'asc' ? 'desc' : 'asc');
    $param['_order'] = $field;
    $url = Url::build(Request::instance()->action(), $param);

    return Request::instance()->param('_order') == $field ?
            "<a href='{$url}' title='点击排序' class='sorting-box sorting-{$sort}'>{$name}</a>" :
            "<a href='{$url}' title='点击排序' class='sorting-box sorting'>{$name}</a>";
}

/**
 * 用于高亮搜索关键词
 * @param string $string 原文本
 * @param string $needle 关键词
 * @param string $class  span标签class名
 * @return mixed
 */
function high_light($string, $needle = '', $class = 'c-red') {
    return $needle !== '' ? str_replace($needle, "<span class='{$class}'>" . $needle . "</span>", $string) : $string;
}

/**
 * 无极限生成树
 * @param array $arr
 * @param int $pid          父id
 * @param $me
 * @return array
 */
function generateTree($arr, $pid, $step) {
    global $tree;
    foreach ($arr as $key => $val) {
        if ($val['pid'] == $pid) {
            $flg = str_repeat('└―', $step);
            $val['name'] = $flg . $val['name'];
            $tree[] = $val;
            generateTree($arr, $val['id'], $step + 1);
        }
    }
    return $tree;
}

/*
  function generateTreeOne($arr,$pid,$step,$tree=array()){


  foreach($arr as $key=>$val) {

  if($val['pid'] == $pid) {
  echo $val['id'].'->'.$pid.'->'.$val['pid']."<br>";
  $flg = str_repeat('└―',$step);
  $val['name'] = $flg.$val['name'];
  $tree[] = $val;
  json_encode($tree); echo "<br>";
  generateTreeOne($arr , $val['id'] ,$step+1,$tree);
  }
  }
  #return json_encode($tree);
  }* */

function generateTreeOne($list, $parent, $level = 0) {
    $treec = array();
    foreach ($list as $value) {
        if ($value['pid'] == $parent) {
            $value['level'] = $level;
            $value['name'] = str_repeat("└―", $value['level']) . $value['name'];
            $treec[] = $value;
            $treec = array_merge($treec, generateTreeOne($list, $value['id'], $level + 1));
        }
    }

    return $treec;
}

/**
 * 把二维数组的id转换成键值
 * @param $items
 */
function setArrKeyId($arr) {
    if (!isset($arr))
        return false;
    $arrs = [];
    foreach ($arr as $key => $value) {
        $arrs[$value['id']] = $value;
    }
    return $arrs;
}

function setArrKeyuserId($arr) {
    if (!isset($arr))
        return false;
    $arrs = [];
    foreach ($arr as $key => $value) {
        $arrs[$value['userid']] = $value;
    }
    return $arrs;
}

function setArrKeyuserUserId($arr) {
    if (!isset($arr))
        return false;
    $arrs = [];
    foreach ($arr as $key => $value) {
        $arrs[$value['userid']] = $value;
    }
    return $arrs;
}

/**
 * 获取一个表的数据 通过id集合
 * @param $tablename
 * @param $ids
 * @param null $field
 * @return bool
 */
function getListByIds($tablename, $ids, $field = null) {
	
    if (!isset($tablename))
        return false;
    if (!isset($ids))
        return false;
    if (is_array($ids))
        $ids = implode(',', $ids);
	$ids = $ids.'0';

    $model = Db::name($tablename);
    $List = $model->where("id in ($ids)")->field($field)->select();
    return $List;
}

/**
 * 通过 用户id获取角色
 * @param $uid
 * @return null|string
 */
function getRoleNameByUid($uid) {
    $AdminRole = new \app\common\model\AdminRole(); //实例化 角色
    $Roles = $AdminRole->getRoleByUid($uid); //获取用户角色列表
    $RolesName = null;
    foreach ($Roles as $Role) {
        $RolesName .= $Role['name'] . ',';
//        $RolesName.=$Role['name'];
    }
    return $RolesName;
//    var_dump($RolesName);die;
}

/*
 *
 * lengthConversionKm
 * @param $leng 长度
 * 百度地图是按米算的所以需要 米换算成公里
 */

function lengthConversionKm($leng) {
    $leng = $leng / 1000;
    return $leng;
}

/*
 *
 * lengthConversion
 * @param $leng 长度
 * 百度地图是按米算的所以需要 公里换算成米
 */

function lengthConversion($leng) {
    $leng = $leng / 1000;
    return $leng;
}

/**
 * 用于显示状态操作按钮
 * @param int $status        0|1|-1状态
 * @param int $id            对象id
 * @param string $field      字段，默认id
 * @param string $controller 默认当前控制器
 * @return string
 */
function show_status($status, $id, $field = 'id', $controller = '') {
    $controller === '' && $controller = Request::instance()->controller();
    switch ($status) {
        // 恢复
        case 0 :
            $ret = '<a href="javascript:;" onclick="ajax_req(\'' . Url::build($controller . '/resume', [$field => $id]) . '\',{},change_status,[this,\'resume\'])" class="label label-success radius" title="点击恢复">恢复</a>';
            break;
        // 禁用
        case 1 :
            $ret = '<a href="javascript:;" onclick="ajax_req(\'' . Url::build($controller . '/forbid', [$field => $id]) . '\',{},change_status,[this,\'forbid\'])" class="label label-warning radius" title="点击禁用">禁用</a>';
            break;
        // 还原
        case -1 :
            $ret = '<a href="javascript:;" onclick="ajax_req(\'' . Url::build($controller . '/recycle', [$field => $id]) . '\')" class="label label-secondary radius" title="点击还原">还原</a>';
            break;
        /*         * **打个补丁 预防id不等于2**** */
        default:
            $ret = '<a href="javascript:;" onclick="ajax_req(\'' . Url::build($controller . '/resume', [$field => $id]) . '\',{},change_status,[this,\'resume\'])" class="label label-success radius" title="点击恢复">状态错误点击恢复</a>';
        /*         * **打个补丁 end**** */
    }

    return $ret;
}

/**
 * 显示状态
 * @param int $status     0|1|-1
 * @param bool $imageShow true只显示图标|false只显示文字
 * @return string
 */
function get_status($status, $imageShow = true) {
    switch ($status) {
        case 0 :
            $showText = '禁用';
            $showImg = '<i class="Hui-iconfont c-warning status" title="禁用">&#xe631;</i>';
            break;
        case -1 :
            $showText = '删除';
            $showImg = '<i class="Hui-iconfont c-danger status" title="删除">&#xe6e2;</i>';
            break;
        case 1 :
        default :
            $showText = '正常';
            $showImg = '<i class="Hui-iconfont c-success status" title="正常">&#xe615;</i>';
    }

    return ($imageShow === true) ? $showImg : $showText;
}

/**
 * 框架内部默认ajax返回
 * @param string $msg      提示信息
 * @param string $redirect 重定向类型 current|parent|''
 * @param string $alert    父层弹框信息
 * @param bool $close      是否关闭当前层
 * @param string $url      重定向地址
 * @param string $data     附加数据
 * @param int $code        错误码
 * @param array $extend    扩展数据
 */
function ajax_return_adv($msg = '操作成功', $redirect = 'parent', $alert = '', $close = false, $url = '', $data = '', $code = 0, $extend = []) {
    $extend['opt'] = [
        'alert' => $alert,
        'close' => $close,
        'redirect' => $redirect,
        'url' => $url,
    ];

    return ajax_return($data, $msg, $code, $extend);
}

/**
 * 返回错误json信息
 */
function ajax_return_adv_error($msg = '', $code = 1, $redirect = '', $alert = '', $close = false, $url = '', $data = '', $extend = []) {
    return ajax_return_adv($msg, $alert, $close, $redirect, $url, $data, $code, $extend);
}

/**
 * ajax数据返回，规范格式
 * @param array $data   返回的数据，默认空数组
 * @param string $msg   信息
 * @param int $code     错误码，0-未出现错误|其他出现错误
 * @param array $extend 扩展数据
 */
function ajax_return($data = [], $msg = "", $code = 0, $extend = []) {
    $ret = ["code" => $code, "msg" => $msg, "data" => $data];
    $ret = array_merge($ret, $extend);

    return Response::create($ret, 'json');
}

/**
 * 返回标准错误json信息
 */
function ajax_return_error($msg = "出现错误", $code = 1, $data = [], $extend = []) {
    return ajax_return($data, $msg, $code, $extend);
}

/**
 * 从二维数组中取出自己要的KEY值
 * @param  array $arrData
 * @param string $key
 * @param $im true 返回逗号分隔
 * @return array
 */
function filter_value($arrData, $key, $im = false) {
    $re = [];
    foreach ($arrData as $k => $v) {
        if (isset($v[$key]))
            $re[] = $v[$key];
    }
    if (!empty($re)) {
        $re = array_flip(array_flip($re));
        sort($re);
    }

    return $im ? implode(',', $re) : $re;
}

/**
 * 重设键，转为array(key=>array())
 * @param array $arr
 * @param string $key
 * @return array
 */
function reset_by_key($arr, $key) {
    $re = [];
    foreach ($arr as $v) {
        $re[$v[$key]] = $v;
    }

    return $re;
}

/**
 * 节点遍历
 *
 * @param        $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int    $root
 *
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0) {
    // 创建Tree
    $tree = [];
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = [];
        foreach ($list as $key => $data) {
            if ($data instanceof \think\Model) {
                $list[$key] = $data->toArray();
            }
            $refer[$data[$pk]] = & $list[$key];
        }

        foreach ($list as $key => $data) {
            // 判断是否存在parent
            if (!isset($list[$key][$child])) {
                $list[$key][$child] = [];
            }
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = & $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = & $refer[$parentId];
                    $parent[$child][] = & $list[$key];
                }
            }
        }
			
    }
	if(empty($tree) && !empty($parent)) $tree = ['0'=>$parent];
    return $tree;
}

/**
 * 统一密码加密方式，如需变动直接修改此处
 * @param $password
 * @return string
 */
function password_hash_tp($password) {
    return hash("md5", trim($password));
}


/**
 * 获取自定义配置
 * @param string|int $name 配置项的key或者value，传key返回value，传value返回key
 * @param string $conf
 * @param bool $key        传递的是否是配置键名，默认是，则返回配置信息
 * @return int|string
 */
function get_conf($name, $conf, $key = true) {
    $arr = config("conf." . $conf);
    if ($key)
        return $arr[$name];
    foreach ($arr as $k => $v) {
        if ($v == $name) {
            return $k;
        }
    }
}

/**
 * 多维数组合并（支持多数组）
 * @return array
 */
function array_merge_multi() {
    $args = func_get_args();
    $array = [];
    foreach ($args as $arg) {
        if (is_array($arg)) {
            foreach ($arg as $k => $v) {
                if (is_array($v)) {
                    $array[$k] = isset($array[$k]) ? $array[$k] : [];
                    $array[$k] = array_merge_multi($array[$k], $v);
                } else {
                    $array[$k] = $v;
                }
            }
        }
    }

    return $array;
}

/**
 * 将list_to_tree的树还原成列表
 * @param array $tree
 * @param string $child
 * @param string $order
 * @param int $level
 * @param null $filter
 * @param array $list
 * @return array
 */
function tree_to_list($tree, $filter = null, $child = '_child', $order = 'id', $level = 0, &$list = []) {
    if (is_array($tree)) {
        if (!is_callable($filter)) {
            $filter = function (&$refer, $level) {
                $refer['level'] = $level;
            };
        }
        foreach ($tree as $key => $value) {
            $refer = $value;
            unset($refer[$child]);
            $filter($refer, $level);
            $list[] = $refer;
            if (isset($value[$child])) {
                tree_to_list($value[$child], $filter, $child, $order, $level + 1, $list);
            }
        }
    }

    return $list;
}

/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list   查询结果
 * @param string $field 排序的字段名
 * @param array $sortBy 排序类型
 *                      asc正向排序 desc逆向排序 nat自然排序
 * @return array|bool
 */
function list_sort_by($list, $field, $sortBy = 'asc') {
    if (is_array($list)) {
        $refer = $resultSet = [];
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortBy) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc': // 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val)
            $resultSet[] = &$list[$key];

        return $resultSet;
	}
   return false;
}
#验证apptoken
#加密方法 md5(userId+token)
function checkToken($token = "",$userId){
    if(empty($token)){return false;}
    if(empty($userId)){return false;}
    // if(strlen($token)!=32){return false;}
    $memberToken = Db::connect("db_config_attendance")->name('member')->where(['id'=>$userId])->field('id,token,tokenTimeOut')->find();
    $myToken = md5(trim($memberToken['id']).trim($memberToken['token']));
    //var_dump($myToken."==".$token);die;
    #大小写判断
    $M_token = strtoupper($token);
    $M_myToken = strtoupper($myToken);

    #token不相等退出
    if($token == $myToken || $M_myToken == $M_token){
        return true;
    }
    return false;
}
/**
 * @todo 将对象转换成数组
 * @param unknown_type $obj
 * @return unknown
 */
function object_to_array($array){
    if(is_object($array)) {
        $array = (array)$array;
    } if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = object_to_array($value);
        }
    }
    return $array;
}


/**
 * 获取指定日期段内每一天的日期
 * @param Date $startdate 开始日期
 * @param Date $enddate  结束日期
 * @return Array
 */
function getDateFromRange($startdate, $enddate){
    $stimestamp = strtotime($startdate);
    $etimestamp = strtotime($enddate);
    // 计算日期段内有多少天
    $days = ($etimestamp-$stimestamp)/86400+1;
    // 保存每天日期
    $date = array();
    for($i=0; $i<$days; $i++){
        $date[] = date('Y-m-d', $stimestamp+(86400*$i));
    }
    return $date;
}

//get curl请求
// @0return Array
function CurlGet($url=""){
    header("Content-type: text/html; charset=utf-8");
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
    curl_setopt($ch, CURLOPT_REFERER, 'https://agk.gandianli.com');
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_TIMEOUT,3);//设置3秒钟 如果3秒没有返回直接丢失
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return json_encode($data);
}